package lingou.homework.postbar.controller;

import jakarta.servlet.http.HttpSession;
import lingou.homework.postbar.controller.proto.resp.Response;
import lingou.homework.postbar.controller.proto.UserView;
import lingou.homework.postbar.controller.tool.*;
import lingou.homework.postbar.domain.User;
import lingou.homework.postbar.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    UserService userService;
    @Autowired
    UserView userView;

    @PostMapping
    Response register(String username, String email, String password) {
        return Chain.of(
                () -> FormatHelper.illegalEmail(email, userService::exists),
                () -> FormatHelper.illegalUsername(username),
                () -> FormatHelper.illegalPassword(password),
                () -> {
                    userService.register(username, email, password);
                    return Response.SUCCESS;
                }
        ).result();
    }
    @GetMapping
    Response exists(String email) {
        return Response.ofSuccess(userService.exists(email));
    }
    @PostMapping("/login")
    Response login(String email, String password, HttpSession session){
        User user = userService.login(email, password);
        if(user == null){
            return Response.ofFailure("密码错误");
        }
        SessionHelper.login(session, user.getUserId());
        return Response.ofSuccess(userView.attachInfo(user));
    }
//    @GetMapping("/login")
//    Response loginStatus(HttpSession session){
//        Long currentUser = SessionHelper.getCurrentUser(session);
//        if(currentUser == null) return SessionHelper.NOT_LOGGED;
//        return Response.ofSuccess(userView.attachInfo(userService.getUser(currentUser)));
//    }
    @PostMapping("/logout")
    Response logout(HttpSession session){
        SessionHelper.logout(session);
        return Response.ofSuccess();
    }

    @GetMapping("/all")
    Response getAllUser(HttpSession session) {
        SessionHelper.checkLogin(session);
        List<User> allUsers = userService.getAllUsers();
        return Response.ofSuccess(Tools.mapList(allUsers,
                user -> userView.attachInfo(user)));
    }
}
